package com.qianyu.demo;

import java.util.*;

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        LinkedList<List<Integer>> res = new LinkedList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int j = i + 1; // left pointer
            int k = nums.length - 1; // right pinter
            int target = -nums[i];
            while (j < k) {
                if (target == nums[j] + nums[k]) {
                    LinkedList<Integer> list = new LinkedList<>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[k]);
                    if (res.peek() != list) { // 使用ArrayList的contains方法会出现超时，因为其底层使用的是遍历，所以这里使用LinkedList的peek方法
                        res.add(list);
                    }
                    j++;
                    k--;
                    while (j < nums.length && nums[j] == nums[j - 1]) {
                        j++;
                    }
                    while (k >= 0 && nums[k] == nums[k + 1]) {
                        k--;
                    }
                } else if (target > nums[j] + nums[k]) {
                    j++;
                } else {
                    k--;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        List<List<Integer>> lists = new Solution().threeSum(nums);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }
}












